﻿using Newtonsoft.Json;

namespace EasyXaf.LowCode.RulesEngineEditors.Models;

public class OutputAggregateOperatorConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(OutputAggregateOperator);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return FromString(reader.Value as string);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(ToString((OutputAggregateOperator)value));
    }

    public static OutputAggregateOperator FromString(string value)
    {
        return value switch
        {
            "count" => OutputAggregateOperator.Count,
            "sum" => OutputAggregateOperator.Sum,
            "avg" => OutputAggregateOperator.Average,
            "max" => OutputAggregateOperator.Max,
            "min" => OutputAggregateOperator.Min,
            "first" => OutputAggregateOperator.First,
            "last" => OutputAggregateOperator.Last,
            _ => OutputAggregateOperator.None
        };
    }

    public static string ToString(OutputAggregateOperator value)
    {
        return value switch
        {
            OutputAggregateOperator.Count => "count",
            OutputAggregateOperator.Sum => "sum",
            OutputAggregateOperator.Average => "avg",
            OutputAggregateOperator.Max => "max",
            OutputAggregateOperator.Min => "min",
            OutputAggregateOperator.First => "first",
            OutputAggregateOperator.Last => "last",
            _ => "none"
        };
    }
}
